import React, { Component } from "react";
import { Alert, Button, Icon, Upload, Divider, Modal } from "antd";
import {
  BasicLayout,
  BasicLayoutSearch,
} from "../../../components/BasicLayout";
// import { Redirect } from 'react-router-dom'
import {
  TableCustomize,
  BasicPagination,
  openModalMessage,
  openSuccessModal,
  compareNum,
} from "../../../components/TableCustomize";
import SearchForm from "./SearchForm";
import { baseUrl, toLead } from "../../../config";
import AddForm from "./AddForm";
import * as APIService from "../../../axios/api_yq";
import { Link } from "react-router-dom";
import { withPermission } from "../../../components/withpermission";
const CreateButton = withPermission(Button, "plus");
const DeleteButton = withPermission(Button, "line");
const DownLoadButton = withPermission(Button, "download");
const UploadButton = withPermission(Button, "upload");
const { confirm } = Modal;
export default class ProcessAllocation extends Component {
  state = {
    dataSource: [],
    inquire: [],
    paging: {},
    visible: false,
    formData: {},
    drawerVisible: false,
    createTime: null,
    one: false,
    loading: false,
    some: null,
    selectedRowKeys: [],
    selectedRows: [],
    advanced: false,
    values: {},
    loginFlag: false,
    control: false,
    buttonList: [],
    astrict: false,
  };
  // 挂载前
  UNSAFE_componentWillMount() {
    this.fetch();
  }
  componentWillUnmount() {
    this.setState = () => {
      return;
    };
  }
  //初始化加载数据
  fetch = (page = 1, size = 100) => {
    const { values } = this.state;
    const buttonList = JSON.parse(localStorage.getItem("buttonList"));
    console.log("这是按钮", buttonList);
    if (buttonList ? buttonList.length !== 0 : null) {
      this.setState({
        buttonList,
      });
    }
    this.setState({
      loading: true,
      paging: { pageNum: page, pageSize: size },
    });
    let a = { pageNum: page, pageSize: size };
    console.log("这是初始化数据", { ...values, ...a });
    setTimeout(() => {
      this.search({ ...values, ...a });
    }, 300);
  };
  // 查询接口
  search = (value) => {
    APIService.queryProcessByCondition(value).then((item) => {
      console.log("查询数据", item);
      if (item.data.code === 200) {
        this.setState({
          dataSource: item.data.data.data,
          // 操作后清除选中
          selectedRowKeys: [],
          selectedRows: [],
          some: null,
          loading: false,
          paging: {
            pageNum: item.data.data.pageNum,
            pageSize: item.data.data.pageSize,
            total: item.data.data.total,
          },
        });
      } else {
        openModalMessage("error", item.data.msg);
      }
    });
  };
  // 新增、修改接口
  addModification = (data) => {
    const { values, paging } = this.state;
    APIService.addProcess(data).then((item) => {
      if (item.data.code === 200) {
        openSuccessModal(item.data.msg);
        this.handleCancel();
        this.search({ ...values, ...paging });
        this.setState({
          formData: {},
        });
      } else {
        this.setState({
          astrict: false,
        });
        openModalMessage("error", item.data.msg);
      }
    });
  };
  //关联班组
  deleteRow1 = (b) => {
    sessionStorage.setItem("data", JSON.stringify(b));
  };
  // 单行删除
  deleteRow2 = (c) => {
    const then = this;
    const { values, paging } = this.state;
    let ids = { ids: [c.id] };
    confirm({
      title: "确认删除当项吗，这将影响其他数据模块?",
      onOk() {
        APIService.deleteProcess(ids).then((item) => {
          if (item.data.code === 200) {
            openSuccessModal("删除成功");
            then.search({ ...values, ...paging });
          } else {
            openModalMessage("error", item.data.msg);
          }
        });
      },
      onCancel() {},
    });
  };
  // 新增数据/修改
  onHandleOk = () => {
    const { formData, astrict } = this.state;
    // console.log(formData.id);
    let id = formData.id;
    this.formDrawer.validateFields((err, value) => {
      if (err) return;
      let amend = { ...value, id };
      // console.log('数据', amend);
      this.setState(
        {
          astrict: true,
        },
        () => {
          this.addModification(amend);
        }
      );
    });
  };
  // 取消
  handleCancel = (e) => {
    //表单重置函数
    this.formAdd && this.formAdd.resetFields();
    this.formDrawer && this.formDrawer.resetFields();
    this.setState({
      visible: false,
      one: false,
      formData: {},
      astrict: false,
    });
  };
  // 条件查询查询
  handleSearch = (value) => {
    console.log("条件查询", value);
    const { paging, values } = this.state;
    let a = { pageNum: paging.pageNum, pageSize: paging.pageSize };
    this.setState({
      values: value,
    });
    this.search({ ...value, ...a });
  };
  // 编辑行数据
  loadData = (value, dataSource) => {
    this.setState(
      {
        loading: true,
      },
      () => {
        this.addModification(value);
      }
    );
  };
  //0新增
  create = () => {
    this.setState({
      one: false,
      visible: true,
    });
  };
  //删除选中
  remove = () => {
    const { selectedRows, some, values, paging } = this.state;
    let a = [...selectedRows];
    let b = [];
    a.forEach((item) => {
      b.push(item.id);
    });
    let ids = { ids: b };
    if (some > 0) {
      APIService.deleteProcess(ids).then((item) => {
        if (item.data.code === 200) {
          openSuccessModal("删除成功");
          this.search({ ...values, ...paging });
        } else {
          openModalMessage("error", item.data.msg);
        }
      });
    } else {
      openModalMessage("error", "请选择数据");
    }
  };
  // 导出模板
  derive = () => {
    APIService.exportExcelDemo1().then((res) => {
      console.log(res);
      //设置下载文件类型为xlsx 不同的类型type也不一样，创建URL对象
      let url = window.URL.createObjectURL(
        new Blob([res.data], {
          type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        })
      );
      // 创建A标签
      let link = document.createElement("a");
      link.style.display = "none";
      link.href = url;
      // 设置的下载文件文件名
      const fileName = decodeURI("工序与班组分配");
      // 触发点击方法
      link.setAttribute("download", fileName);
      document.body.appendChild(link);
      link.click();
    });
  };
  // 导出选中
  derive2 = () => {
    const { selectedRows, some } = this.state;
    if (some > 0 && some !== null && some !== 0) {
      console.log("导出数据", selectedRows);
      APIService.exportExcel11(selectedRows).then((res) => {
        //设置下载文件类型为xlsx 不同的类型type也不一样，创建URL对象
        let url = window.URL.createObjectURL(
          new Blob([res.data], {
            type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
          })
        );
        // 创建A标签
        let link = document.createElement("a");
        link.style.display = "none";
        link.href = url;
        // 设置的下载文件文件名
        const fileName = decodeURI("工序与班组分配");
        // 触发点击方法
        link.setAttribute("download", fileName);
        document.body.appendChild(link);
        link.click();
      });
    } else {
      openModalMessage("error", "请选中导出项");
    }
  };
  // 重置
  cz = () => {
    this.setState(
      {
        values: null,
      },
      () => {
        this.fetch();
      }
    );
  };
  // 高级查询
  advancedss = () => {
    console.log("高级查询");
    this.setState({ advanced: !this.state.advanced });
  };
  // 按钮点击事件
  // btnClick = (a) => {
  //     if (a === 0) {
  //         this.create()
  //     }
  //     if (a === 1) {
  //         this.remove()
  //     }
  //     if (a === 2) {
  //         this.derive()
  //     }
  //     if (a === 3) {
  //         this.derive2()
  //     }
  // }
  render() {
    const then = this;
    const {
      astrict,
      buttonList,
      control,
      selectedRowKeys,
      visible,
      advanced,
      some,
      one,
      paging,
      loading,
      dataSource,
      formData,
      drawerVisible,
    } = this.state;
    const rowSelection = {
      type: "checkbox",
      selectedRowKeys: selectedRowKeys,
      onChange: (selectedRowKeys, selectedRows) => {
        let some = [...selectedRows].length;
        this.setState(
          {
            some: some,
            selectedRows: selectedRows,
            selectedRowKeys: selectedRowKeys,
          },
          () => {
            console.log(
              "选中个数",
              this.state.some,
              "选中详细数据",
              this.state.selectedRows
            );
          }
        );
        if (some === 0 || some === null) {
          this.setState({
            control: false,
          });
        } else {
          this.setState({
            control: true,
          });
        }
      },
    };
    const columns = [
      {
        title: "序号",
        dataIndex: "number",
        width: 50,
        align: "center",
        render: (text, record, index) => <div>{index + 1}</div>,
      },
      {
        title: "工序编码",
        width: 100,
        dataIndex: "procedureCode",
        sorter: (a, b) => compareNum(a.procedureCode, b.procedureCode),
      },
      {
        title: "工序名称",
        width: 200,
        dataIndex: "procedureName",
        sorter: (a, b) => compareNum(a.procedureName, b.procedureName),
        editable: true,
      },
      {
        title: "工序类型",
        width: 200,
        dataIndex: "procedureType",
        sorter: (a, b) => compareNum(a.procedureType, b.procedureType),
        render: (text, record, index) => (
          <div>{text === "1" ? "试机工序" : "生产工序"}</div>
        ),
      },
      {
        title: "关联班组",
        width: 500,
        dataIndex: "teamCode",
        sorter: (a, b) => compareNum(a.teamCode, b.teamCode),
      },
      {
        title: "备注",
        width: 200,
        dataIndex: "remark",
        sorter: (a, b) => compareNum(a.remark, b.remark),
        editable: true,
      },
      {
        title: "创建人",
        width: 100,
        dataIndex: "creatorId",
        sorter: (a, b) => compareNum(a.creatorId, b.creatorId),
      },
      {
        title: "创建时间",
        width: 150,
        dataIndex: "createTime",
        sorter: (a, b) => compareNum(a.createTime, b.createTime),
      },
      {
        title: "操作",
        dataIndex: "opts",
        width: 130,
        render: (text, record) => (
          <div>
            <Link to="/relevancy" onClick={this.deleteRow1.bind(this, record)}>
              关联班组
            </Link>
            {/* <a onClick={this.deleteRow1.bind(this, record)}>{'关联班组'}</a> */}
            <Divider type="vertical" />
            <a onClick={this.deleteRow2.bind(this, record)}>{"删除"}</a>
          </div>
        ),
      },
      { dataIndex: "" },
    ];
    // 导入
    const propss = {
      name: "file",
      action: `${baseUrl}${toLead}/processTeamAllocation/importExcel`,
      accept: ".xls,.xlsx",
      method: "post",
      showUploadList: true,
      headers: {
        userId: localStorage.getItem("userId"),
        Token: localStorage.getItem("token"),
      },
      onChange(info) {
        console.log("这是", info);
        if (info.file.status !== "uploading") {
          console.log("这是什么", info.file, info.fileList);
        }
        if (info.file.status === "done") {
          openSuccessModal("导入成功");
          then.fetch();
        } else if (info.file.status === "error") {
          openModalMessage("error", "错误");
        }
      },
    };
    return (
      <div>
        <BasicLayoutSearch>
          <SearchForm
            onSearch={this.handleSearch}
            onClick={this.cz}
            onClick1={this.advancedss}
            advanced={advanced}
          />
        </BasicLayoutSearch>
        {control === true ? (
          <Alert
            message={
              <div>
                已选择 <span style={{ color: "#1890ff" }}>{some}</span> 项
              </div>
            }
            type="info"
            showIcon
            style={{ width: "99%", margin: "auto" }}
          ></Alert>
        ) : null}

        <BasicLayout
          name="工序与班组分配"
          icon="table"
          buttons={[
            <CreateButton key={1} onClick={this.create} icon="plus" />,
            <DeleteButton key={2} onClick={this.remove} icon="line" />,
            <DownLoadButton
              key={3}
              onClick={this.derive}
              icon="plus"
              text="模板导出"
            />,
            <DownLoadButton
              key={4}
              onClick={this.derive2}
              icon="download"
              text="导出选中"
            />,
            <Upload {...propss} key={6}>
              <UploadButton icon="upload" />
            </Upload>,
            // <Button key={1} onClick={this.create} type="primary" icon='plus'>新增</Button>,
            // <Button key={2} onClick={this.remove} type="primary" icon='line'>删除</Button>,
            // <Button key={3} onClick={this.derive} type="primary" icon='download'>模板导出</Button>,
            // <Button key={5} onClick={this.derive2} type="primary" icon='download'>导出选中</Button>,
            // <Upload {...propss} key={4}>
            //     <Button type="primary">
            //         <Icon type="upload" /> 导入
            //     </Button>
            // </Upload>,
          ]}
        >
          <TableCustomize
            rowSelection={rowSelection}
            columns={columns}
            rowKey={(record) => record.id}
            dataSource={dataSource}
            pagination={false}
            loading={loading}
            allowDrafting={true}
            allowEditable={this.loadData}
            scroll={{ x: true, y: 600 }}
            rowClassName={(record, index) => {
              return [
                "editable-row",
                index % 2 === 0 ? "editable-row" : "editable-row12",
              ];
            }}
          />
          <BasicPagination
            pageNum={paging.pageNum}
            pageSize={paging.pageSize}
            total={paging.total}
            loadData={this.fetch}
          />
        </BasicLayout>
        <Modal
          confirmLoading={astrict}
          visible={visible}
          destroyOnClose
          title={"新增"}
          onOk={this.onHandleOk}
          onCancel={this.handleCancel}
          okText="保存"
          cancelText="取消"
        >
          <AddForm
            onOk={this.onHandleOk}
            formData={formData}
            ref={(node) => (this.formDrawer = node)}
            one={one}
          />
        </Modal>
      </div>
    );
  }
}
